<template>
	<!-- 自定义导航栏 -->
	<CustomNavBar />
	<!-- 滚动容器 -->
	<scroll-view scroll-y class="home" @scrolltolower="onScrolltolower" refresher-enabled @refresherrefresh="onRefresher"
		:refresher-triggered="isTriggered">
		<!-- 骨架图,在网络请求没有完成时显示 -->
		<PageSkeleton v-if="isLoading" />
		<template v-else>
			<!-- 轮播图 -->
			<XtxSwiper :bannerList="bannerList" />
			<!-- 分类面板 -->
			<CategoryPannel :categoryList="categoryList" />
			<!-- 热门推荐 -->
			<HotPannel :hotList="hotList" />
			<!-- 猜你喜欢 -->
			<XtxGuess ref="guessRef" />
		</template>
	</scroll-view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app'
	import CustomNavBar from './components/CustomNavBar.vue'
	import XtxSwiper from '@/components/XtxSwiper.vue'
	import CategoryPannel from './components/CategoryPannel.vue'
	import HotPannel from './components/HotPannel.vue'
	import XtxGuess from '@/components/XtxGuess.vue'
	import PageSkeleton from './components/PageSkeleton.vue'
	import { onMounted, ref } from 'vue';
	import { BannerItem, CategoryItem, HotItem } from '../../types/home';
	import { getBannerAPI, getCategoryAPI, getHotAPI } from '../../services/home';

	//页面是否正在加载
	const isLoading = ref(true)
	// 获取轮播图数据
	const bannerList = ref<BannerItem[]>([])
	async function getBannerData() {
		const res = await getBannerAPI()
		bannerList.value = res.result
	}

	// 获取分类数据
	const categoryList = ref<CategoryItem[]>([])
	async function getCategoryData() {
		const res = await getCategoryAPI()
		categoryList.value = res.result
	}

	// 获取热门商品数据
	const hotList = ref<HotItem[]>([])
	async function getHotData() {
		const res = await getHotAPI()
		hotList.value = res.result
	}

	// 页面挂载时获取数据
	onLoad(async () => {
		isLoading.value = true
		//Promise.all 用于处理多个 Promise 的并发执行
		await Promise.all([getBannerData(), getCategoryData(), getHotData()])
		isLoading.value = false
	})

	//父组件主动调取子组件的函数，用ref通信
	const guessRef = ref()
	//触底触发
	function onScrolltolower() {
		//获取更多guessGoods
		guessRef.value.getMore()
	}

	// 当前下拉刷新状态
	const isTriggered = ref(false)
	//下拉刷新触发
	async function onRefresher() {
		//开启动画
		isTriggered.value = true
		//清空猜你喜欢组件数据
		guessRef.value.resetData()
		//刷新
		await Promise.all([
			getBannerData(),
			getCategoryData(),
			getHotData(),
			guessRef.value.getMore(),
		])

		uni.showToast({ icon: 'none', title: '刷新成功' })
		//关闭动画
		isTriggered.value = false
	}
</script>

<style lang="scss">
	page {
		background-color: #f7f7f7;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.home {
		flex: 1;
	}
</style>